# baseApi
# 2024/10/19
# author:www
import inspect
import json
import traceback
from idlelib.iomenu import encoding

import pytest
import requests

from configs.config import host
from utils.handle_log import log
from utils.handle_yaml import get_yaml_data


class BaseApi:
    def __init__(self,token=None):
        print(token)
        if token:
            self.header = {'Authorization': 'Bearer ' + token[0],'Uaaid':token[1] }
        else:
            self.header = {'Content-Type': 'application/json'}
        try:
            # 通过类名作为键获取对应类的数据，
            # self.__class__  返回当前实例所属的类对象
            # self.__class__.__name__ 获取当前实例所属类的名称，作为字符串
            self.data = get_yaml_data('../data/apiConfig.yaml')[self.__class__.__name__]
            print('调用基类的子类是：', self.__class__.__name__)
        except KeyError:
            print('继承基类的子类名称在yaml文中未找到！！！调用基类的子类是：', self.__class__.__name__)


    def request_send(self,request_body,file=False):
        '''
        封装请求函数
        :param request_body: 请求体-请求参数(body)；参数形式：1、params跟在请求后面name=qq&sex=1;2、data;3、json;4、file
        :return: 返回响应结果
        '''
        try:
            function_name = inspect.stack()[1][3]
            data = self.data[function_name]
            # if type(request_body) is dict:
            #     request_body = json.dumps(request_body)
            #     request_body = json.loads(request_body)
            # elif type(request_body) is str:
            #     request_body = json.loads(request_body)
            # else:
            #     request_body = request_body
            # 判断，如果接口请求方式是文件类型，则使用files接收请求
            if file:
                response_body = requests.request(method=data['method'], url=f'{host}' + data['url'], files=request_body,
                                                 headers=self.header)
            else:
                response_body = requests.request(method=data['method'], url=f'{host}' + data['url'], json=request_body,
                                                 headers=self.header)
            if response_body.status_code == 200:
                print('服务器响应结果编码格式：',response_body.encoding)
                # response_body.encoding ='gbk'
                # 如果程序编码与服务器响应编码不一致，可以设置响应格式编码来接收数据
                return response_body.json()
            else:
                print('服务器响应结果编码格式：', response_body.encoding)
                return response_body.text
        except Exception as e:
            log.error(traceback.format_exc())
            raise e


    def getPage(self,request_body):
        '''
        封装：查询列表
        :param request_body:
        :return:
        '''
        return self.request_send(request_body)


    def saveOrUpdate(self,request_body):
        '''
        封装：修改
        :param request_body:
        :return:
        '''
        return self.request_send(request_body)


    def upload(self,file_dir):
        '''
        封装：查询列表
        :param file_dir:图片名称，图片对象，图片类型（三个参数）
        :return:
        '''
        # D:\py_project\Health_SaaS_Interface\data\imageupload.png
        file_name = file_dir.split('\\')[-1]
        file_type = file_name.split('.')[-1]
        # rb 文件以二进制形式读取
        user_file = {'file':(file_name,open(file_name,'rb'),file_type)}
        return self.request_send(user_file,file=True)




class BaseAssert:
    @classmethod  # 使用类名直接调用方法
    def define_assert(cls,actually,expected):
        '''
        捕获断言失败的异常
        :param actually: 实际结果
        :param expected: 期望结果
        :return:
        '''
        try:
            assert actually == expected,f"Expected {expected} , but got {actually}"
        except Exception as e:
            log.error(traceback.format_exc())
            pytest.fail(f"Expected JSON response, but got: {actually}")
            raise e
